package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.smile.api.OperateLogApi;
import com.smile.api.OrganizationApi;
import com.smile.api.OssApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.gps.GeoConvertUtils;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.page.R;
import com.smile.commons.time.TimeUtils;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.dto.DroneDTO;
import com.smile.model.dto.request.*;
import com.smile.model.response.response.*;
import com.smile.model.request.GetOrganizationByIdRequest;
import com.smile.model.response.GetOrganizationByIdResponse;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.AirportService;
import com.smile.service.DroneService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

@Service
@Slf4j
public class AirportServiceImpl implements AirportService {

    @Autowired
    private OssApi ossApi;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private OrganizationApi organizationApi;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private DeviceModelMapper deviceModelMapper;
    private ReentrantLock reentrantLock = new ReentrantLock();


    @Autowired
    private AirportInfoMapper airportInfoMapper;

    @Override
    @Transactional
    public Boolean addAirport(AddAirportRequestDTO addAirportRequestDTO) throws IOException {
        try {
            reentrantLock.lock();

            Long startTime = System.nanoTime();

            QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("delete_status", 0);
            queryWrapper.eq("airport_name", addAirportRequestDTO.getAirportName());
            List<FeisuanAirport> feisuanAirports = airportMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(feisuanAirports)) {
                throw new RuntimeException("机场已存在");
            }

            // 1. 创建机场对象并设置基础属性
            FeisuanAirport feisuanAirport = new FeisuanAirport();
            BeanUtil.copyProperties(addAirportRequestDTO, feisuanAirport);


//            double[] doubles = GeoConvertUtils.gaodeToGps(feisuanAirport.getLatitude().doubleValue(), feisuanAirport.getLongitude().doubleValue());
//            feisuanAirport.setLatitude(new BigDecimal(Double.toString(doubles[0])));
//            feisuanAirport.setLongitude(new BigDecimal(Double.toString(doubles[1])));

            feisuanAirport.setCreateTime(LocalDateTime.now());
            feisuanAirport.setModifyTime(LocalDateTime.now());
            feisuanAirport.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
            feisuanAirport.setStatus(1);
            feisuanAirport.setTotalTaskCount(0L);
            feisuanAirport.setTotalTaskTime(0L);
            feisuanAirport.setDeleteStatus(false);
            feisuanAirport.setTotalTaskDistance(0L);

            // 4. 保存机场信息
            airportMapper.insert(feisuanAirport);

            // 5. 处理关联的无人机（新增绑定状态检查）
            List<Long> droneIds = addAirportRequestDTO.getDroneIds();
            if (CollUtil.isNotEmpty(droneIds)) {
                // 5.1 检查无人机绑定状态
                QueryWrapper<FeisuanAirportDrone> bindCheckWrapper = new QueryWrapper<>();
                bindCheckWrapper.in("drone_id", droneIds)
                ; // 假设0表示未删除

                List<FeisuanAirportDrone> existingBinds = airportDroneMapper.selectList(bindCheckWrapper);

                // 5.2 收集已绑定的无人机ID
                Set<Long> boundDroneIds = existingBinds.stream()
                        .map(FeisuanAirportDrone::getDroneId)
                        .collect(Collectors.toSet());

                // 5.3 找出未绑定的无人机
                List<Long> validDroneIds = droneIds.stream()
                        .filter(droneId -> !boundDroneIds.contains(droneId))
                        .collect(Collectors.toList());

                // 5.4 如果有重复绑定，记录日志或抛出异常
                if (validDroneIds.size() != droneIds.size()) {
                    log.warn("检测到{}架无人机已绑定，跳过绑定: {}",
                            droneIds.size() - validDroneIds.size(),
                            droneIds.stream()
                                    .filter(boundDroneIds::contains)
                                    .collect(Collectors.toList()));
                }

                // 5.5 只保存未绑定的无人机
                if (CollUtil.isNotEmpty(validDroneIds)) {
                    List<FeisuanAirportDrone> relations = validDroneIds.stream()
                            .map(droneId -> {
                                FeisuanAirportDrone relation = new FeisuanAirportDrone();
                                relation.setAirportId(feisuanAirport.getId());
                                relation.setDroneId(droneId);
//                            relation.(false); // 设置删除状态
                                return relation;
                            })
                            .collect(Collectors.toList());

                    // 批量保存关联关系
                    Db.saveBatch(relations);
                }
            }

            // 6. 记录操作日志
            Long endTime = System.nanoTime();
            AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
            addOperateLogRequest.setOperateModule("设备模块");
            addOperateLogRequest.setOperateName("新增机场");
            addOperateLogRequest.setOperateResult(Boolean.TRUE);
            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
            addOperateLogRequest.setOperateType(1);
            addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
            addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
            addOperateLogRequest.setTimes(endTime - startTime);
            operateLogApi.addOperateLogRequest(addOperateLogRequest);
        } finally {
            reentrantLock.unlock();
        }

        return Boolean.TRUE;
    }

    @Override
    public Page<GetAirportListResponseDTO> getAirportList(GetAirportListRequestDTO getAirportListRequestDTO) {
        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(getAirportListRequestDTO)) {
            if (ObjectUtil.isNotNull(getAirportListRequestDTO.getStatus())) {
                queryWrapper.eq("status", getAirportListRequestDTO.getStatus());
            }
            if (StrUtil.isNotBlank(getAirportListRequestDTO.getAirportName())) {
                queryWrapper.eq("airport_name", getAirportListRequestDTO.getAirportName());
            }

            if (StrUtil.isNotBlank(getAirportListRequestDTO.getOrganizationIds())) {
                String[] ids = getAirportListRequestDTO.getOrganizationIds().split(",");
                queryWrapper.in("organization_id", ids);
            }
        }
        log.info("开始查询机场列表,当前时间为:{}", LocalDateTime.now());
        Page<FeisuanAirport> page = airportMapper.selectPage(new Page<>(getAirportListRequestDTO.getCurrentPage(), getAirportListRequestDTO.getPageSize()), queryWrapper);
        log.info("查询机场列表完毕,当前时间为:{}", LocalDateTime.now());


        Page<GetAirportListResponseDTO> getAirportListResponseDTOPage = MyBatisPlusPageConverter.convertPage(page, GetAirportListResponseDTO.class);

        List<Long> collect = page.getRecords().stream().map(i -> i.getId()).collect(Collectors.toList());

        List<FeisuanAirportDrone> feisuanAirportDrones = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(collect)) {

            QueryWrapper<FeisuanAirportDrone> feisuanAirportDroneQueryWrapper = new QueryWrapper<>();

            feisuanAirportDroneQueryWrapper.in("airport_id", page.getRecords().stream().map(i -> i.getId()).collect(Collectors.toList()));
            List<FeisuanAirportDrone> feisuanAirportDrones1 = airportDroneMapper.selectList(feisuanAirportDroneQueryWrapper);

            feisuanAirportDrones.addAll(feisuanAirportDrones1);

        }
///**
// * 机场sn
// */
//        private String gatewaySn;
//
//        private String organizationName;
//
//        private Long organizationId;

        getAirportListResponseDTOPage.setRecords(page.getRecords().stream().map(i -> {
            String message = "风速:< " + i.getWindSpeedThreshold() + " m/s 降雨：< " + i.getRainfallThreshold() + " mm";
            GetAirportListResponseDTO getAirportListResponseDTO = BeanUtil.copyProperties(i, GetAirportListResponseDTO.class);
            getAirportListResponseDTO.setEnvironmentThreshold(message);
            if (i.getStatus() == 1) {
                getAirportListResponseDTO.setStatus("在线");
            } else if (i.getStatus() == 2) {
                getAirportListResponseDTO.setStatus("离线");
            }
            //根据更新时间判断是否在线
            Duration duration =Duration.between(i.getModifyTime(),LocalDateTime.now());
            System.out.println("时间相差:");
            System.out.println(duration.toSeconds());
            System.out.println(duration.getSeconds());
            if(duration.getSeconds()>20){
                getAirportListResponseDTO.setStatus("离线");
            }
            getAirportListResponseDTO.setGatewaySn(i.getGatewaySn());
            getAirportListResponseDTO.setOrganizationId(i.getOrganizationId());
            SmilePlusOrganization smilePlusOrganization = organizationMapper.selectById(i.getOrganizationId());
            if (ObjectUtil.isNotNull(smilePlusOrganization)) {
                getAirportListResponseDTO.setOrganizationName(smilePlusOrganization.getOrganizationName());
            }

            System.out.println("无人机数量=" + feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()));

            getAirportListResponseDTO.setDroneNums(Integer.valueOf(feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()).size()).longValue());
            QueryWrapper<FeisuanAirportDrone> feisuanAirportDroneQueryWrapper = new QueryWrapper<>();

            feisuanAirportDroneQueryWrapper.eq("airport_id", i.getId());
            feisuanAirportDroneQueryWrapper.last("limit 1");
            FeisuanAirportDrone feisuanAirportDrones2 = airportDroneMapper.selectOne(feisuanAirportDroneQueryWrapper);
            if (ObjectUtil.isNotNull(feisuanAirportDrones2)) {
                FeisuanDrone  feisuanDrone = droneMapper.selectById(feisuanAirportDrones2.getDroneId());
                if (ObjectUtil.isNotNull(feisuanDrone)) {
                    getAirportListResponseDTO.setModelId(feisuanDrone.getModelId());
                    getAirportListResponseDTO.setDeviceModelKey(feisuanDrone.getDeviceModelKey());
                    FeisuanDeviceModel deviceModel = deviceModelMapper.selectById(feisuanDrone.getModelId());
                    if (ObjectUtil.isNotNull(deviceModel)) {
                        getAirportListResponseDTO.setModelName(deviceModel.getModelName());
                    }
                }
            }

            return getAirportListResponseDTO;
        }).collect(Collectors.toList()));
        return getAirportListResponseDTOPage;
    }

    @Override
    public Boolean editAirport(EditAirportRequestDTO editAirportRequestDTO) throws IOException {
        try {
            reentrantLock.lock();
            Long startTime = System.nanoTime();
            QueryWrapper<FeisuanAirport> queryWrapperA = new QueryWrapper<>();
            queryWrapperA.eq("airport_name", editAirportRequestDTO.getAirportName());
            queryWrapperA.ne("id",editAirportRequestDTO.getId());
            queryWrapperA.last("limit 1");
            FeisuanAirport feisuanAirportOther = airportMapper.selectOne(queryWrapperA);
            if (ObjectUtil.isNotNull(feisuanAirportOther)) {
                return false;
            }
            UpdateWrapper<FeisuanAirport> updateWrapper = new UpdateWrapper<>();
            if (ObjectUtil.isNotNull(editAirportRequestDTO)) {
                QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", editAirportRequestDTO.getId());
                FeisuanAirport feisuanAirport = airportMapper.selectOne(queryWrapper);

                updateWrapper.set(StrUtil.isNotBlank(editAirportRequestDTO.getAirportName()), "airport_name", editAirportRequestDTO.getAirportName());
                updateWrapper.set(StrUtil.isNotBlank(editAirportRequestDTO.getImageUrl()), "image_url", editAirportRequestDTO.getImageUrl());
                updateWrapper.set(StrUtil.isNotBlank(editAirportRequestDTO.getAddress()), "address", editAirportRequestDTO.getAddress());
                if (CollectionUtil.isNotEmpty(editAirportRequestDTO.getDroneIds())) {

//                    if (ObjectUtil.isNotNull(editAirportRequestDTO.getLongitude()) && ObjectUtil.isNotNull(editAirportRequestDTO.getLatitude())) {
//
//                        CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(editAirportRequestDTO.getLongitude().doubleValue(), editAirportRequestDTO.getLatitude().doubleValue());
//                        feisuanAirport.setLatitude(new BigDecimal(String.valueOf(coordinate.getLatitude())));
//                        feisuanAirport.setLongitude(new BigDecimal(String.valueOf(coordinate.getLongitude())));
//
//                    }

                    UpdateWrapper<FeisuanAirportDrone> updateWrapper1 = new UpdateWrapper<>();
                    updateWrapper1.eq("airport_id", editAirportRequestDTO.getId());
                    airportDroneMapper.delete(updateWrapper1);
                    List<FeisuanAirportDrone> collect = editAirportRequestDTO.getDroneIds().stream().map(i -> {
                        FeisuanAirportDrone feisuanAirportDrone = new FeisuanAirportDrone();
                        feisuanAirportDrone.setAirportId(editAirportRequestDTO.getId());
                        feisuanAirportDrone.setDroneId(i);
                        return feisuanAirportDrone;
                    }).collect(Collectors.toList());
                    Db.saveBatch(collect);
                }

                if (ObjectUtil.isNotNull(editAirportRequestDTO.getGatewaySn())) {
                    updateWrapper.set("gateway_sn", editAirportRequestDTO.getGatewaySn());
                }
                if (ObjectUtil.isNotNull(editAirportRequestDTO.getOrganizationId())) {
                    updateWrapper.set("organization_id", editAirportRequestDTO.getOrganizationId());
                }

                if (ObjectUtil.isNotNull(editAirportRequestDTO.getLongitude()) && ObjectUtil.isNotNull(editAirportRequestDTO.getLatitude())) {

//                    feisuanAirport.setLatitude(bigDecimals[1]);
//                    feisuanAirport.setLongitude(bigDecimals[0]);

                    updateWrapper.set("longitude", editAirportRequestDTO.getLongitude());
                    updateWrapper.set("latitude", editAirportRequestDTO.getLatitude());
//                    CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(editAirportRequestDTO.getLongitude().doubleValue(), editAirportRequestDTO.getLatitude().doubleValue());
//                    editAirportRequestDTO.setLongitude(new BigDecimal(String.valueOf(coordinate.getLongitude())));
//                    editAirportRequestDTO.setLatitude(new BigDecimal(String.valueOf(coordinate.getLatitude())));
                }

                updateWrapper.eq("id", editAirportRequestDTO.getId());

                if (StrUtil.isNotBlank(editAirportRequestDTO.getDescription())) {
                    updateWrapper.set("description", editAirportRequestDTO.getDescription());
                }
                if (StrUtil.isNotBlank(editAirportRequestDTO.getIpAddress())) {
                    updateWrapper.set("ip_address", editAirportRequestDTO.getIpAddress());
                }
                if (StrUtil.isNotBlank(editAirportRequestDTO.getVideoAddress())) {
                    updateWrapper.set("video_address", editAirportRequestDTO.getVideoAddress());
                }
                if (StrUtil.isNotBlank(editAirportRequestDTO.getGateway())) {
                    updateWrapper.set("gateway", editAirportRequestDTO.getGateway());

                }
                if (ObjectUtil.isNotNull(editAirportRequestDTO.getLatitude())) {
                    updateWrapper.set("latitude", editAirportRequestDTO.getLatitude());
                }
                if (ObjectUtil.isNotNull(editAirportRequestDTO.getWindSpeedThreshold())) {
                    updateWrapper.set("wind_speed_threshold", editAirportRequestDTO.getWindSpeedThreshold());
                }
                if (ObjectUtil.isNotNull(editAirportRequestDTO.getRainfallThreshold())) {
                    updateWrapper.set("rainfall_threshold", editAirportRequestDTO.getRainfallThreshold());
                }


            }
            updateWrapper.set(StrUtil.isNotBlank(editAirportRequestDTO.getAirportName()), "airport_name", editAirportRequestDTO.getAirportName());
            airportMapper.update(new FeisuanAirport(), updateWrapper);

            Long endTime = System.nanoTime();

            AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
            addOperateLogRequest.setOperateModule("设备模块");
            addOperateLogRequest.setOperateName("编辑机场设备");
            addOperateLogRequest.setOperateResult(Boolean.TRUE);
            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
            addOperateLogRequest.setOperateType(2);
            addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
            addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
            addOperateLogRequest.setTimes(endTime - startTime);
            operateLogApi.addOperateLogRequest(addOperateLogRequest);
        } finally {
            reentrantLock.unlock();
        }

        return Boolean.TRUE;
    }

    @Override
    public GetAirportByIdResponseDTO getAirportById(GetAirportByIdRequestDTO getAirportByIdRequestDTO) {
        if (ObjectUtil.isNotNull(getAirportByIdRequestDTO) && ObjectUtil.isNotNull(getAirportByIdRequestDTO.getId())) {
            FeisuanAirport feisuanAirport = airportMapper.selectById(getAirportByIdRequestDTO.getId());
            if (ObjectUtil.isNull(feisuanAirport)) {
                return null;
            }
//            if (!feisuanAirport.getDeleteStatus()) {
            GetAirportByIdResponseDTO getAirportByIdResponseDTO = BeanUtil.copyProperties(feisuanAirport, GetAirportByIdResponseDTO.class);
//            getAirportByIdResponseDTO.setAirportMaintenanceInfo();
            GetAirportMaintenanceInfoResponseDTO airportMaintenanceInfoResponseDTO = new GetAirportMaintenanceInfoResponseDTO();

            //lng lat
//            BigDecimal[] bigDecimals = CoordinateTransformUtil.wgs84ToGcj02(feisuanAirport.getLongitude().doubleValue(), feisuanAirport.getLatitude().doubleValue());
//            getAirportByIdResponseDTO.setLongitude(bigDecimals[0]);
//            getAirportByIdResponseDTO.setLatitude(bigDecimals[1]);


            QueryWrapper<FeisuanAirportDrone> airportDroneQueryWrapper = new QueryWrapper<>();
            airportDroneQueryWrapper.eq("airport_id", getAirportByIdRequestDTO.getId());
            List<FeisuanAirportDrone> feisuanAirportDrones1 = airportDroneMapper.selectList(airportDroneQueryWrapper);
            QueryWrapper<FeisuanDrone> feisuanDroneQueryWrapper = new QueryWrapper<>();
            List<Long> collect = feisuanAirportDrones1.stream().map(i -> i.getDroneId()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {

                feisuanDroneQueryWrapper.in("id", collect);
                List<FeisuanDrone> feisuanDrones = droneMapper.selectList(feisuanDroneQueryWrapper);

                List<DroneDTO> collect1 = feisuanDrones.stream().map(i -> {
                    DroneDTO droneDTO = BeanUtil.copyProperties(i, DroneDTO.class);
                    switch (i.getStatus()) {
                        case 1:
                            droneDTO.setStatus("作业中");
                            break;
                        case 2:
                            droneDTO.setStatus("待命");
                            break;
                        case 3:
                            droneDTO.setStatus("离线");
                            break;
                    }
                    droneDTO.setTotalTaskTime(TimeUtils.toChineseTime(i.getTotalTaskTime()));
                    return droneDTO;
                }).collect(Collectors.toList());
                airportMaintenanceInfoResponseDTO.setFirmwareVersion(feisuanAirport.getFirmwareVersion());
                airportMaintenanceInfoResponseDTO.setFirmwareUpgradeStatus(feisuanAirport.getFirmwareUpgradeStatus());
                airportMaintenanceInfoResponseDTO.setLastMaintainTime(feisuanAirport.getLastMaintainTime());
                airportMaintenanceInfoResponseDTO.setLastMaintainType(feisuanAirport.getLastMaintainType());




                String gatewaySn = feisuanAirport.getGatewaySn();
                QueryWrapper<FeisuanAirportInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("gateway_sn", gatewaySn);
                List<FeisuanAirportInfo> feisuanAirportInfos = airportInfoMapper.selectList(queryWrapper);

                if (CollectionUtil.isNotEmpty(feisuanAirportInfos)) {
                    FeisuanAirportInfo feisuanAirportInfo = feisuanAirportInfos.get(0);
                    airportMaintenanceInfoResponseDTO.setAlarmState(feisuanAirportInfo.getAlarmState());
                    airportMaintenanceInfoResponseDTO.setModeCode(feisuanAirportInfo.getModeCode());

                    GetDroneBatteryMaintenanceInfoResponseDTO getDroneBatteryMaintenanceInfoResponseDTO = new GetDroneBatteryMaintenanceInfoResponseDTO();
//                    //设置电池电量
//                    getDroneBatteryMaintenanceInfoResponseDTO.setCapacityPercent(feisuanAirportInfo.getCapacityPercent());
                    //设置固件版本
                    getDroneBatteryMaintenanceInfoResponseDTO.setFirmwareVersion(StrUtil.isNotBlank(feisuanAirportInfo.getFirmwareVersion()) ? feisuanAirportInfo.getFirmwareVersion() : "");
                    //设置固件升级情况
                    if (ObjectUtil.isNull(feisuanAirportInfo.getFirmwareUpgradeStatus())) {
//                        getDroneBatteryMaintenanceInfoResponseDTO.setFirmwareUpgradeStatus();
                    } else {
//                        getDroneBatteryMaintenanceInfoResponseDTO.setFirmwareUpgradeStatus(feisuanAirportInfo.getFirmwareUpgradeStatus() == 0 ? "未升级" : "升级中");
                    }

                    String droneBatteryMaintenanceInfo = feisuanAirportInfo.getDroneBatteryMaintenanceInfo();

                }


                getAirportByIdResponseDTO.setDroneDTOs(collect1);
                getAirportByIdResponseDTO.setAirportMaintenanceInfo(airportMaintenanceInfoResponseDTO);
                getAirportByIdResponseDTO.setTotalTaskTime(TimeUtils.toChineseTime(feisuanAirport.getTotalTaskTime()));

                switch (feisuanAirport.getStatus()) {
                    case 1:
                        getAirportByIdResponseDTO.setStatus("在线");
                        break;
                    case 2:
                        getAirportByIdResponseDTO.setStatus("离线");
                        break;
                }
//根据更新时间判断是否在线
                Duration duration =Duration.between(feisuanAirport.getModifyTime(),LocalDateTime.now());
                System.out.println("时间相差:");
                System.out.println(duration.toSeconds());
                System.out.println(duration.getSeconds());
                if(duration.getSeconds()>20){
                    getAirportByIdResponseDTO.setStatus("离线");
                }
                GetOrganizationByIdRequest getOrganizationByIdRequest = new GetOrganizationByIdRequest();
                getOrganizationByIdRequest.setId(feisuanAirport.getOrganizationId());
                R<GetOrganizationByIdResponse> organizationById = organizationApi.getOrganizationById(getOrganizationByIdRequest);
                if (ObjectUtil.isNotNull(organizationById) || ObjectUtil.isNotNull(organizationById.getData())) {
                    getAirportByIdResponseDTO.setOrganizationName(organizationById.getData().getOrganizationName());
                }


            } else {
                getAirportByIdResponseDTO.setDroneDTOs(Collections.emptyList());
            }
            return getAirportByIdResponseDTO;
//            } else {
//                throw new RuntimeException("机场不存在");
//            }
        }
        throw new RuntimeException("传递的参数为空");
    }

    @Override
    public Boolean deleteAirport(Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new RuntimeException("id不能为空");
        }

        Long startTime = System.nanoTime();

        airportMapper.deleteById(id);

        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("设备模块");
        addOperateLogRequest.setOperateName("删除无人机设备");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }

    @Override
    public Map<Long, GetAirportByIdsResponseDTO> getAirportByIds(List<Long> ids) {

        List<FeisuanAirport> feisuanAirports = airportMapper.selectBatchIds(ids);
        List<GetAirportByIdsResponseDTO> getAirportByIdsResponseDTOS = BeanUtil.copyToList(feisuanAirports, GetAirportByIdsResponseDTO.class);
        Map<Long, GetAirportByIdsResponseDTO> collect = getAirportByIdsResponseDTOS.stream().collect((toMap(GetAirportByIdsResponseDTO::getId, Function.identity(), (u1, u2) -> u1)));


        return collect;
    }

    @Override
    public List<GetAirportListResponseDTO> getAirportList1(GetAirportListRequestDTO getAirportListRequestDTO) {

        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
//        if (ObjectUtil.isNotNull(getAirportListRequestDTO)) {
//            if (ObjectUtil.isNotNull(getAirportListRequestDTO.getStatus())) {
//                queryWrapper.eq("status", getAirportListRequestDTO.getStatus());
//            }
//            if (StrUtil.isNotBlank(getAirportListRequestDTO.getAirportName())) {
//                queryWrapper.eq("airport_name", getAirportListRequestDTO.getAirportName());
//            }
//        }
        List<FeisuanAirport> list = airportMapper.selectList(queryWrapper);


        List<FeisuanAirport> collect1 = list.stream().map(i -> {
//            BigDecimal[] bigDecimals = CoordinateTransformUtil.wgs84ToGcj02(i.getLongitude(), i.getLatitude());
            FeisuanAirport feisuanAirport = BeanUtil.copyProperties(i, FeisuanAirport.class);
//            feisuanAirport.setLatitude(bigDecimals[1]);
//            feisuanAirport.setLongitude(bigDecimals[0]);

            double[] doubles = GeoConvertUtils.gpsToGaode(i.getLatitude().doubleValue(), i.getLongitude().doubleValue());
            feisuanAirport.setLatitude(new BigDecimal(Double.toString(doubles[0])));
            feisuanAirport.setLongitude(new BigDecimal(Double.toString(doubles[1])));

            return feisuanAirport;
        }).collect(Collectors.toList());

//        Page<GetAirportListResponseDTO> getAirportListResponseDTOPage = MyBatisPlusPageConverter.convertPage(page, GetAirportListResponseDTO.class);
//
//        List<Long> collect = page.getRecords().stream().map(i -> i.getId()).collect(Collectors.toList());

        List<FeisuanAirportDrone> feisuanAirportDrones = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(collect1)) {

            QueryWrapper<FeisuanAirportDrone> feisuanAirportDroneQueryWrapper = new QueryWrapper<>();

            feisuanAirportDroneQueryWrapper.in("airport_id", collect1.stream().map(i -> i.getId()).collect(Collectors.toList()));
            List<FeisuanAirportDrone> feisuanAirportDrones1 = airportDroneMapper.selectList(feisuanAirportDroneQueryWrapper);

            feisuanAirportDrones.addAll(feisuanAirportDrones1);

        }


        List<GetAirportListResponseDTO> collect = collect1.stream().map(i -> {
            String message = "风速:< " + i.getWindSpeedThreshold() + " m/s 降雨：< " + i.getRainfallThreshold() + " mm";
            GetAirportListResponseDTO getAirportListResponseDTO = BeanUtil.copyProperties(i, GetAirportListResponseDTO.class);
            getAirportListResponseDTO.setEnvironmentThreshold(message);
            if (i.getStatus() == 1) {

                getAirportListResponseDTO.setStatus("在线");
            } else if (i.getStatus() == 2) {
                getAirportListResponseDTO.setStatus("离线");
            }

            System.out.println("无人机数量=" + feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()));

            getAirportListResponseDTO.setDroneNums(Integer.valueOf(feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()).size()).longValue());

            return getAirportListResponseDTO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Boolean deleteAirportByOrganizationId(Long id) {
        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", id);
        List<FeisuanAirport> feisuanAirports = airportMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(feisuanAirports)) {
            Long id1 = feisuanAirports.get(0).getId();
            QueryWrapper<FeisuanAirportDrone> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("airport_id", id1);
            airportDroneMapper.delete(queryWrapper1);
        }

        airportMapper.delete(queryWrapper);


        return Boolean.TRUE;
    }
}
